<!DOCTYPE html>
<!--
 This code was created by Federico Elles which
 can be found at http://code.google.com/p/predictionwiz/
 
 Please let me know about errors and improvements via info@3x3Links.com or the link above.
-->
<html>
<head>
	<meta charset=utf-8 />
	<title>Admin - Prediction Wizard</title>
	<link rel="stylesheet" type="text/css" media="screen" href="/stylesheets/main.css" />
	<link rel="shortcut icon" href="/stylesheets/favicon.png" />
	<link type="text/css" href="/css/smoothness/jquery-ui-1.8.6.custom.css" rel="Stylesheet" />	
	<script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>
	<script type="text/javascript" src="/js/jquery-ui-1.8.6.custom.min.js"></script>
	<!--[if IE]>
		<script src="https://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->		
</head>
<body>
<div class="div_menu_adm">
<a href="/">Back</a>
| <a target="_blank" href="https://cloud.google.com/console/project/{{project}}">Google Cloud Console</a>
| <a href="/adm/exit">Sign out</a>
</div>


<h1 title="Home">
<img src="/stylesheets/logo.png">
Prediction Wizard Admin v1.6
</h1>

<div id="tabs">
	<ul>
		<li><a href="#tabs-1">Models</a></li>
		<!--<li><a href="#tabs-2">Storage</a></li>-->
	</ul>
	<div id="tabs-1">

<!--
  Models
  
  
-->


<table class="tbl_results">
{% if records %}
<tr>

<th style="width:15%">Datafile</th>
<th style="width:15%">Caption</th>
<th style="width:20%">Utility</th>
<th style="width:15%">Action</th>
<th style="width:25%">Result</th>
<th style="width:5%">Delete</th>
<th style="width:5%">Public</th>
</tr>
  {% for record in records %}
	<tr>
	  <td>{{ record.datafile }}</td>
	  <td>{{ record.caption }}</td>
	  <td><span id="span_{{ record.key }}">{{ record.utility }}<br><a class="a_utility" tid="{{ record.key }}" href="#">edit</a></span> <textarea class="ta_utility" id="ta_{{ record.key }}">{{ record.utility }}</textarea></td>
	  <td>
	    <button id="btn_train_{{ record.key }}" onClick="action('{{ record.key }}','train','{{ record.datafile }}','{{ record.project }}')">Train</button>
		<span title="Since start of training." id="span_train_{{ record.key }}"></span>
	    <button id="btn_trainstatus_{{ record.key }}" onClick="action('{{ record.key }}','trainstatus','{{ record.datafile }}','{{ record.project }}')">Status</button>
	  </td>
	  <td id="result_{{ record.key }}"></td>	  
	  <td>	  
		<form action="/adm/delete" method="POST">
          <input type="hidden" name="key" value="{{ record.key }}" />
		  <button>x</button>
        </form>
	  </td>
	  <td><input type="checkbox" {% if record.public %}checked{% endif %} disabled /></td>	  
	</tr>
  {% endfor %}
{% else %}
  <tr><td colspan="5">No data models available</td></tr>
{% endif %}

</table>

<p>Result Data Type:
<select id="datatype">
  <option value="json">JSON</option>
  <option value="html">HTML</option>
</select>
</p>

<hr>

<p><b>Create a new data model:</b></p>
<form action="/adm/new" method="POST">
  <table class="tbl_results">
  <tr>
    <td>Bucket/ Learning file name*</td>
	<td><input name="bucket" class="localstoragesave" id="inp_new_bucket" />/<input name="datafile" /></td>
  </tr>
  <tr>
    <td>Caption</td>
	<td><input name="caption" /></td>
  </tr>  
  <tr>
    <td><b>Project</b></td>
	<td><input name="project" />
	<p >New mandatory field. 
		Go to <a href="https://cloud.google.com/console">Cloud Console</a>, 
		select the project where Prediction API is enabled, copy the Project Number displayed on top, e.g. "1712387192873".
		If this field is not provided, the default value is taken over from config.py: {{ project }}
	</p>
	</td>
  </tr>    
  <tr>
    <td>Public</td>
	<td><input type="checkbox" name="public" /> Share model with the world</td>
  </tr>    
  <tr>
    <td>Storage Check</td>
	<td>
	  <input id="inp_create_model_check1" type="checkbox"/><label for="inp_create_model_check1">
	    I created the bucket in my Google Storage (<a target="_blank" href="https://sandbox.google.com/storage/">Google Cloud Storage</a>).
	  </label>
	  <br/>
	  <input id="inp_create_model_check2" type="checkbox"/><label for="inp_create_model_check2">
	    I uploaded the learning file into my Google Storage (<a target="_blank" href="https://sandbox.google.com/storage/">Google Cloud Storage</a>).
	  </label>
	
	</td>
  </tr>   
  <tr>
    <td></td>
	<td><button>Create</button></td>
  </tr>  
  </table>  
  <p><b>Hint:</b> Hello World training file: <a href="http://code.google.com/apis/predict/docs/language_id.txt">language_id.txt</a></p>
</form>

<hr>

Synchronize Prediction Models with local DB. Only possible of models have been created with the PredictionWiz or the model.id equals the model.storageDataLocation.

<form action="/adm/sync">
<input type="submit" value="Sync" />
</form>


<!--
  End
-->
	
	</div>
	
	
<!--
<div id="tabs-3">


<iframe height="60%" width="100%" src="https://sandbox.google.com/storage/#wiz" scrolling="yes" frameborder="0"> 
</iframe> 
	</div>

  End
 -->	
	
</div>

</body>


<script type="text/javascript">
//
// Enable Tabs
//
var $tabs = $( "#tabs" ).tabs();

$('.ta_utility').hide();

$('.a_utility').click(function(e){
  e.preventDefault();
  var tid = $(this).attr('tid');
  if ($('#ta_'+tid).val() == 'None'){
    $('#ta_'+tid).val('Use format:\nName:Number\nEnglish:123');
  }
  $('#ta_'+tid).show();
  $('#span_'+tid).hide();
});

// ----- //
// Setup //
// ----- //


// ------ //
// Models //
// ------ //

//
// Training Timer
//
// based upon http://www.mcfedries.com/javascript/timer.asp
var secs;
var timerID = null;
var timerRunning = false;
var delay = 1000;
var modelkey = '';
var maxdur = 600;

// via http://www.electrictoolbox.com/pad-number-zeroes-javascript-improved/
function pad(number, length) { 
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

function InitializeTimer(key)
{
    secs = 0; //ten minutes
    StopTheClock(key);
    StartTheTimer(key);
}

function StopTheClock(key)
{
    if(timerRunning){
        clearTimeout(timerID);
		$('#span_train_'+modelkey).html('');
	}
	modelkey = key;
    timerRunning = false;
}

function StartTheTimer(key)
{
    if (secs>600)
    {
        StopTheClock(key);
        $('#span_train_'+key).html('Error');
    }
    else
    {
        $('#span_train_'+key).html(pad(Math.round(secs/60),2)+':'+pad(secs%60,2));
        secs = secs + 1;
        timerRunning = true;
        timerID = self.setTimeout("StartTheTimer('"+key+"')", delay);
    }
}

//
// Train or Status click
//
var data_debug = {};
function action(key, urlsuffix, datafile, project){
  $('#result_'+key).html("Working...");
  $('#btn_'+urlsuffix+'_'+key).attr('disabled','disabled');
  var utility = $('#ta_'+key).val();
  $.ajax({url: '/adm/api/'+urlsuffix,
    dataType: $('#datatype').val(),
	type: 'POST',
    data: {datafile: datafile, key:key, utility : utility, project: project},
	success: function(data) {
	  data_debug = data;
      if ($('#datatype').val() == 'json'){
		if (urlsuffix == 'trainstatus'){ 
			if (data.trainingStatus == 'ERROR'){
			  html = 'ERROR'
			} else {
				if (data.error){
					html = 'ERROR: ' + data.error.message
				} else {	
					if (data.trainingStatus == "ERROR: TRAINING JOB NOT FOUND" || data.trainingStatus == "RUNNING"){
						html = data.trainingStatus;
					} else {
						if (data.modelInfo.modelType == 'regression'){
							html = 'MSE: ' + data.modelInfo.meanSquaredError + ' - ' + data.trainingStatus;
						}
						if (data.modelInfo.modelType == 'classification'){
							html = '';
							if (data.modelInfo.classWeightedAccuracy){
								html+='Weighted ACY: ' +data.modelInfo.classWeightedAccuracy +'<br>';
							}
							html += 'ACY: ' + data.modelInfo.classificationAccuracy + ' - ' + data.trainingStatus;
						}
						if (data.modelInfo.numberInstances == '0'){
							html = 'ERROR: Number of valid data instances used in the trained model = 0';
						}
					}
				}
			}
		}
	    if (urlsuffix == 'train'){ 
			if (data.error){
				html = 'ERROR: ' + data.error.message
			} else {
				html = "Training has started for '" + data.id + '. Please check Status.';
				$('#span_train_'+key).html('Start');
				InitializeTimer(key);
			}
		}
	  } else {
	    html = data;
	  }
	  $('#result_'+key).html(html); 
	  setStats(key,html)
	  $('#btn_'+urlsuffix+'_'+key).attr('disabled','');
    },
	error: function(XMLHttpRequest, textStatus, errorThrown) {
	  $('#btn_'+urlsuffix+'_'+key).attr('disabled','');
	  try {
	    if (errorThrown.indexOf('HTTPError = 401') > -1){
	      result = 'Authentification failed';
	    } else {
          result = textStatus + errorThrown;
	    } 
		$('#result_'+key).html(result);
	  } catch (e) {
	    $('#result_'+key).html(errorThrown);
	  }
    }	
  });
}


//
// LOCALSTORAGE FOR RESULTS
//
var getStats = function(model){
  stats = localStorage.getItem("model_"+model)
  if (typeof stats  == "undefined"){
    return false
  } 
  return stats
}

var setStats = function(model,data){
  localStorage.setItem("model_"+model,data);
}


//
// Initial Training Status Check
//
{% for record in records %}

if (!getStats('{{ record.key }}')){
  action('{{ record.key }}','trainstatus','{{ record.datafile }}');
} else {
  $('#result_{{ record.key }}').html(getStats('{{ record.key }}')); 
}
{% endfor %}


//
// save values for input files in localstorage
//
$(function() {
  $('.localstoragesave').each(function(index) {
  	sid = $(this).attr('id');
  	if (sid){
  	  val = localStorage.getItem("po_"+sid);
	  type = $(this).attr('type');
  	  if (val){
	    if (type == 'checkbox'){
		  if (val == 'true'){
		    $(this).attr('checked', true);
		  } else {
		    $(this).attr('checked', false);
		  }
		} else {
  	      $(this).val(val);
		}
  	  }
  	  //set onchange event for all
 	  $(this).change(function() {
  	    sid = $(this).attr('id');
		type = $(this).attr('type');
		val = $(this).val();
	    if (type == 'checkbox'){  
          val = $(this).attr('checked');
		} else {
		  val = $(this).val();
		}
        localStorage.setItem("po_"+sid,val);		
      });
    }
  });
});


//
// H1 Link
//
$('h1').click(function(){
  location.href='/';
});
 

</script>

</html>